package com.tmall.testgen.client.genfile.genxml;

import java.io.File;
import java.io.FileOutputStream;

import com.thoughtworks.xstream.XStream;
import com.tmall.testgen.client.genfile.genjava.bo.MethodSnap;
import com.tmall.testgen.client.genfile.genproject.ProjectGenerator;
import com.tmall.testgen.common.bo.interact.back.DBInfo;
import com.tmall.testgen.common.util.FileUtil;


/**
 *   xml文件生成
 * 与测试类同名，入参 出参
 * @author haojia
 * @date 2014-07-04
 */
public class XMLFileOperator {

	public final  static int INPUT=1;
	public final  static int OUTPUT=2;
	
	private static final String  SUFFIX=".xml";
	
	public static void  toXML(String fileFullPath,Object o) throws Exception{
		 XStream xstream = new XStream(); 
		  String xml = xstream.toXML(o);
		  
		  xml=xml.replaceAll(ClassInfoForXML.class.getName(), ProjectGenerator.commonpackage+".ClassInfo");
		  xml=xml.replaceAll(DBInfo.class.getName(), ProjectGenerator.commonpackage+"bo.DBInfo");
		  xml=xml.replaceAll(MethodSnap.class.getName(), ProjectGenerator.commonpackage+".bo.MethodSnap");
		  writeToFile(fileFullPath,xml);
	}
	
	public static <T> T getObject(String filePath,boolean needSuffix) throws Exception{
		String content=readFile(filePath,needSuffix);
		XStream xstream = new XStream(); 
		 return  (T) xstream.fromXML(content); 
	}
	
	private static String getFilePath(String filePath){
		return filePath+SUFFIX;
	}
	private static  void writeToFile(String filePath,String content) throws Exception{
		String path=getFilePath(filePath);
		
		File file=new File(path);
        if(file.exists())
        	file.delete();
        
        File folder=new File(filePath.substring(0, filePath.lastIndexOf("/")));
        if(!folder.exists())
        	folder.mkdirs();
        
        file.createNewFile();
        
        FileOutputStream out=new FileOutputStream(file,true);        
        out.write(content.toString().getBytes("utf-8")); 
        out.close();
	}
	
	private static String readFile(String  filePath,boolean needSuffix) throws Exception{
		String path=filePath;
		if(needSuffix)
			path=getFilePath(filePath);
		
		File file=new File(path);
        if(!file.exists()){
        	throw new Exception("文件不存在"); 
        }
        	
        return FileUtil.readFile(filePath);
	}
}
